//
//  PInformationViewController.m
//  Tiger
//
//  Created by 龚 杰 on 12-7-5.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "PInformationViewController.h"
#import "AsyncImageView.h"
#import "PInformationCell.h"
#import "NewsDetailsViewController.h"
#import <QuartzCore/QuartzCore.h>

#define kCustomRowCount     5

#define kNewsID				@"newsID"
#define kTitle				@"title"

#define TagWhiteLabel 0x100
#define TagWhiteLabelDown 0x101

static NSString *PlaceholderCellIdentifier = @"PlaceholderCell";
@interface PInformationViewController ()

@end

@implementation PInformationViewController
@synthesize parsedDataArray;
@synthesize myImageView;
@synthesize dict;

//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        // Custom initialization
//    }
//    return self;
//}

- (id)init
{
    if (self = [super init]) {
        self.parsedDataArray = [[NSMutableArray alloc] init];
        self.myImageView = [[NSMutableArray alloc] init];
        parsedCellArray = [[NSMutableArray alloc] init];
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"top.png"] forBarMetrics: UIBarMetricsDefault];
        self.navigationController.navigationBar.clipsToBounds = YES;
        
    }
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"top.png"]];
	self.navigationController.navigationBar.tintColor =  [UIColor colorWithRed:33.0/255 green:32.0/255 blue:32.0/255 alpha:1.0];

	// Do any additional setup after loading the view.
    
    m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 
                                                                self.view.frame.size.height-80) style:UITableViewStyleGrouped];
    [m_tableView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"screen_bg"]]];
    [m_tableView setDelegate:self];
    [m_tableView setDataSource:self];

    [self.view addSubview:m_tableView];
    [self sendRequestPayInfo];
}
- (void)CreateCell:(NSDictionary*)dicts
{
    PInformationCell *cell = [[[PInformationCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                        reuseIdentifier:PlaceholderCellIdentifier] autorelease];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSString *st_newsID = [dicts objectForKey:kNewsID];
    cell.newsID = [st_newsID intValue];
    cell.m_PicURL = [dicts objectForKey:@"picUrl"];
    [cell sendRequestPayInfo];
    [parsedCellArray addObject:cell];

}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


-(void)sendRequestPayInfo
{
	NSURL* serverURL = [NSURL URLWithString:URL_NewsList];
	ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:serverURL];
	request.tag = -1;
	[request setValidatesSecureCertificate:NO];
	[request setDelegate:self];
	[request startAsynchronous];
}

#pragma mark ASIHTTPRequestDelegate methods
- (void)requestStarted:(ASIHTTPRequest *)request
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}


- (void)requestFinished:(ASIHTTPRequest *)request;
{
    NSLog(@"%@",[request responseString]);
	NSData *responseData = [request responseData];
	NSString *responseStr = [[[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding] autorelease];
	if (request.tag < 0) 
	{
		NSDictionary *tdict = [responseStr JSONValue];
		self.parsedDataArray = [tdict objectForKey:@"items"];
        
        [myImageView removeAllObjects];
//        int index =0;
        for (NSDictionary* infodic in parsedDataArray) {
//            AsyncImageView* tImgs =[[AsyncImageView alloc] initWithFrame:CGRectMake(10,10, 280, 200)];
//            tImgs._numStateRequested = need_Request;
//            tImgs._imageRequestURL = [infodic objectForKey:@"picUrl"];
//            NSLog(@"%@",tImgs._imageRequestURL);
//            tImgs.m_BoolSetImage = YES;
//            [myImageView addObject:tImgs];
//            if (index==0) {
//                [tImgs customLoadImageFromURL];
//                [self.view addSubview:tImgs];
//            }
//            [tImgs release];  
//            index++;
            [self CreateCell:infodic];
        }
        
		[m_tableView reloadData];
	}
	else {
		NSLog(@"recved bad data !");
	}
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"无可用的网络连接" delegate:self 
										   cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
	[alert addButtonWithTitle:@"确定"];
	[alert show];
	
}


#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([parsedDataArray count] > 0) {
        return 300;
    }
	return 55.0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    NSDictionary* disc =  (NSDictionary*)[parsedDataArray objectAtIndex:indexPath.section];
//    [self TimeCountDown:disc];
}


#pragma mark UITableViewDataSource
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	int count = [parsedDataArray count];
    if (count == 0)
	{
        return kCustomRowCount;
    }
    return 1;
	
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    int num = [parsedDataArray count];
    if (num > 0) {
        return num;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	static NSString* CellIdentifier = @"Cellidentifier";
	
	int nodeCount = [self.parsedDataArray count];
	//NSLog(@"nodeCount = %d", nodeCount);
	if (nodeCount == 0 && indexPath.row == 0)
	{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
										   reuseIdentifier:PlaceholderCellIdentifier] autorelease];   
            cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
		cell.detailTextLabel.text = @"数据加载中，请稍后…";
		
		return cell;
    }
    

	return [parsedCellArray objectAtIndex:indexPath.section];
}

- (void)TimeCountDown:(NSDictionary*)dicts
{
	NewsDetailsViewController *viewController = [[NewsDetailsViewController alloc] initWithNibName:@"NewsDetailsViewController" bundle:nil];
	viewController.hidesBottomBarWhenPushed = YES;
	
	NSString *st_newsID = [dicts objectForKey:kNewsID];
	viewController.newsID = [st_newsID intValue];
	
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
								   initWithTitle:@"行业资讯" 
								   style:UIBarButtonItemStylePlain 
								   target:self
								   action:nil];
	self.navigationItem.backBarButtonItem = backButton;
	//导航自带的动画
	[self.navigationController pushViewController:viewController animated:YES];
	[viewController release];;
}
- (void)dealloc
{
    [parsedDataArray release];
    [parsedCellArray release];
    [myImageView release];
    [m_tableView release];
    [dict release];
    [super dealloc];
}
@end
